// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq.Expressions;
using SnapObjects.Commons;

namespace SnapObjects.Expressions
{
    internal class CompileTypeSynchronizer : TypeSynchronizer<Expression>
    {
        protected override Expression Convert(Expression node, Type type)
        {
            return Expression.Convert(node, type);
        }

        protected override Type GetType(Expression node)
        {
            return node.Type;
        }

        protected override Expression ToString(Expression node)
        {
            var toString = Expression.Call(
                node, typeof(object).GetMethod("ToString"));

            if (node.Type.IsValueType && !node.Type.IsNullable())
            {
                return toString;
            }

            var nullExpr = Expression.Constant(null, node.Type);

            var nullEqual = Expression.Equal(nullExpr, node);

            var numStr = Expression.Constant(null, typeof(string));

            return Expression.Condition(nullEqual, numStr, toString);
        }
    }
}
